<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" v-if="avatar" class="avatar" />
      <!-- <img src="../../../assets/images/avatar.jpg" alt="" v-else /> -->
      <img src="../../../assets/images/avatar.jpg" alt="" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" style="display: none" ref="iptRef" @change="onfileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      // 用户头像值base64
      avatar: ''
    }
  },
  methods: {
    // 点击触发input的file
    chooseImg() {
      this.$refs.iptRef.click()
    },
    // 是否选择图片
    onfileChange(e) {
      const files = e.target.files
      if (files.length !== 0) {
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = e => {
          // console.log(e.target.result)
          this.avatar = e.target.result
        }
      } else {
        this.avatar = ''
      }
    },
    // 更换头像
    async uploadAvatar() {
      const { data: res } = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code !== 0) return this.$message.error('上传头像失败')
      this.$message.success('上传头像成功')
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.avatar {
  width: 400px;
  height: 300px;
}
</style>
